<template>
  <div class="forum-add-container">
    <!-- 顶部导航栏 -->
    <VanNavBar
      title="发布论坛"
      class="forum-add-header"
      :border="false"
      left-text="取消"
      right-text="发布"
      @click-left="handleCancel"
      @click-right="handlePublish"
    />

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <!-- 发布表单 -->
      <div class="publish-form">
        <!-- 标题输入 -->
        <VanField
          v-model="forumForm.title"
          placeholder="请输入标题（5-50字）"
          :maxlength="50"
          show-word-limit
          class="title-input"
        />

        <!-- 内容输入 -->
        <VanField
          v-model="forumForm.content"
          type="textarea"
          placeholder="请输入内容（10-500字）"
          :maxlength="500"
          show-word-limit
          rows="6"
          class="content-input"
        />

        <!-- 图片上传 -->
        <div class="image-upload-section">
          <div class="section-title">添加封面图</div>
          
          <!-- 已选图片预览 -->
          <div v-if="forumForm.coverImage" class="image-preview">
            <img :src="forumForm.coverImage" alt="封面图" />
            <VanIcon name="clear" class="delete-icon" @click="removeImage" />
          </div>
          
          <!-- 图片选择按钮 -->
          <div v-else class="upload-btn" @click="selectImage">
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleFileChange"
            />
            <VanIcon name="plus" size="24" />
            <span>选择图片</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载中状态 -->
    <VanLoading v-if="loading" class="loading-overlay" />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from '../utils/axios.js';
import { client, getFileNameUUID } from '../utils/alioss.ts';

const router = useRouter();
const fileInput = ref(null);
const loading = ref(false);

// 论坛表单数据
const forumForm = reactive({
  title: '',
  content: '',
  coverImage: ''
});

// 选择图片
const selectImage = () => {
  fileInput.value?.click();
};

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型和大小
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (!validTypes.includes(file.type)) {
    return alert('请选择有效的图片文件（JPG、PNG、GIF、WEBP）');
  }
  
  if (file.size > 5 * 1024 * 1024) {
    return alert('图片大小不能超过5MB');
  }

  try {
    loading.value = true;
    // 上传图片到阿里云OSS
    const imageUrl = await uploadImageToOSS(file);
    forumForm.coverImage = imageUrl;
    // 清空input，以便重复选择同一张图片
    event.target.value = '';
  } catch (error) {
    console.error('上传图片失败:', error);
    alert('上传图片失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 上传图片到阿里云OSS
const uploadImageToOSS = async (file) => {
  try {
    // 创建OSS客户端
    const ossClient = client();
    
    // 生成随机文件名
    const fileName = getFileNameUUID();
    const fileExtension = file.name.split('.').pop().toLowerCase();
    const objectName = `forum/${fileName}.${fileExtension}`;
    
    // 上传文件
    const result = await ossClient.put(objectName, file);
    
    // 返回完整的图片URL
    return `https://${ossClient.options.bucket}.oss-cn-hangzhou.aliyuncs.com/${result.name}`;
  } catch (error) {
    console.error('OSS上传失败:', error);
    throw error;
  }
};

// 移除图片
const removeImage = () => {
  forumForm.coverImage = '';
};

// 验证表单
const validateForm = () => {
  if (!forumForm.title.trim() || forumForm.title.length < 5 || forumForm.title.length > 50) {
    alert('请输入5-50字的标题');
    return false;
  }
  
  if (!forumForm.content.trim() || forumForm.content.length < 10 || forumForm.content.length > 500) {
    alert('请输入10-500字的内容');
    return false;
  }
  
  return true;
};

// 发布论坛
const handlePublish = async () => {
    const user = JSON.parse(sessionStorage.getItem("user"))
  if (!validateForm()) return;

  try {
    loading.value = true;
    
    // 准备提交数据
    const formData = {
      title: forumForm.title.trim(),
      content: forumForm.content.trim(),
      coverImage: forumForm.coverImage || '',
      authorId:user.userId,
      likes:0,
      collects:0,
      comments:0
    };
    
    // 调用发布接口
    const res = await axios.post('/api/forumAdd', formData);
    
    if (res.code === 200) {
      alert('发布成功');
      // 返回论坛列表页
      router.push('/forum');
    } else {
      alert(res.msg || '发布失败');
    }
  } catch (error) {
    console.error('发布失败:', error);
    alert('发布失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 取消发布
const handleCancel = () => {
  // 如果表单有内容，询问是否确认离开
  if (forumForm.title.trim() || forumForm.content.trim() || forumForm.coverImage) {
    if (confirm('确定要取消发布吗？已填写的内容将不会保存。')) {
      router.push('/forum');
    }
  } else {
    router.push('/forum');
  }
};
</script>

<style lang="less" scoped>
.forum-add-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.forum-add-header {
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  
  :deep(.van-nav-bar__title) {
    font-weight: 500;
  }
  
  :deep(.van-nav-bar__left) {
    color: #666;
  }
  
  :deep(.van-nav-bar__right) {
    color: #ff2442;
  }
}

.content-wrapper {
  padding: 16px;
  background-color: white;
  margin: 8px 0;
}

.publish-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.title-input {
  :deep(.van-cell) {
    padding: 0;
    font-size: 18px;
  }
  
  :deep(.van-field__word-limit) {
    font-size: 12px;
    color: #999;
  }
}

.content-input {
  :deep(.van-cell) {
    padding: 0;
  }
  
  :deep(.van-field__control) {
    font-size: 16px;
    line-height: 1.6;
    min-height: 120px;
  }
  
  :deep(.van-field__word-limit) {
    font-size: 12px;
    color: #999;
  }
}

.image-upload-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-title {
  font-size: 15px;
  color: #333;
  font-weight: 500;
}

.upload-btn {
  width: 100%;
  height: 120px;
  border: 1px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #ff2442;
    color: #ff2442;
  }
  
  span {
    margin-top: 8px;
    font-size: 14px;
  }
}

.image-preview {
  width: 100%;
  height: 180px;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .delete-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
</style>